
'use client';
import { useState, useEffect } from 'react'
import { ApiPromise, WsProvider, Keyring } from '@polkadot/api'
import { atom, useAtom, useSetAtom, useAtomValue } from 'jotai'
import { atomWithReset, RESET } from 'jotai/utils'
import { custom, createWalletClient } from 'viem'
import { mainnet } from 'viem/chains'
import dedent from 'dedent'
import { CheckCircleIcon, ExclamationCircleIcon, ArrowPathIcon, LightBulbIcon, ArrowTopRightOnSquareIcon } from '@heroicons/react/20/solid'
import { getMappingAccount, signAndSend, signAndSendEvm, signMessage } from 'evm-account-mapping-sdk'
const formatter = new Intl.NumberFormat('en-US')

let api, walletClient;

export function Main() {
    const [balance, setBalance] = useState(BigInt(0))
    const [isPending, setIsPending] = useState(false)
    const [trxId, setTrxId] = useState()
    const [mappedAccount, setMappedAccount] = useState()

    async function init() {
        setIsPending(true);
        api = await ApiPromise.create({
            provider: new WsProvider("wss://testnet-rpc1.cess.cloud/ws/"),
            noInitWarn: true,
        });
        console.log('init ok');
        setIsPending(false);
    }
    async function conn() {
        walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) })
        const [address] = await walletClient.requestAddresses();
        console.log({ address })
        const SS58Prefix = (api.consts?.system?.ss58Prefix).toNumber();
        let ma = await getMappingAccount(api, walletClient, { address }, { SS58Prefix });
        setMappedAccount(ma);
    }
    // async function signAndSend() {
    //     try {
    //         setIsPending(true)
    //         setTrxId('')
    //         const keyring = new Keyring({ type: 'sr25519' })
    //         const alice = keyring.addFromUri('//Alice')
    //         const result = await signAndSend(api.tx.balances.transferAllowDeath(mappedAccount.substrateAddress, 1e12 * 10), alice)
    //         const trId = result.status.asInBlock.toHex()
    //         setTrxId(trId)
    //     } finally {
    //         setIsPending(false)
    //     }
    // }
    async function transferToAddress() {
        try {
            let data = {
                amount: 10000000,
                address: "cXh5StobuVP4B7mGH9xn8dSsDtXks4qLAou8ZdkZ6DbB6zzxe"
            };
            setIsPending(true)
            setTrxId('')
            const amount = (Number(data.amount) * 1e4).toFixed(0)
            const result = await signAndSendEvm(
                api.tx.balances.transferAllowDeath(data.address, BigInt(1e8) * BigInt(amount)),
                api,
                walletClient,
                mappedAccount, []
            )
            const trId = result.status.asInBlock.toHex()
            setTrxId(trId)
        } finally {
            setIsPending(false)
        }
    }
    async function signMsg() {
        try {
            let msg = "hello";
            setIsPending(true)
            let result = await signMessage(walletClient, { address: mappedAccount.evmAddress }, msg);
            console.log({ result })
        } finally {
            setIsPending(false)
        }
    }

    function sub() {
        let unsub = () => { }
        (async function () {
            // await init();
            // await conn();
            unsub = await api.query.system.account(
                mappedAccount.substrateAddress,
                (info) => setBalance(info.data.free.toBigInt()))
        })()
        return () => {
            setBalance(BigInt(0))
            unsub && unsub()
        }
    }

    useEffect(() => {

    }, [mappedAccount])


    return (<div>
        <h1>Test</h1>
        <div>
            evmAddress:{mappedAccount?.evmAddress}<br />
            substrateAddress:{mappedAccount?.substrateAddress}<br />
            Balance:{formatter.format(Number(balance / BigInt(1e8)) / 1e4)}<br />
            trxId:{trxId}<br />
            isPending:{isPending}<br />
            {isPending?<ArrowPathIcon className="w-4 h-4 animate-spin" />:""}
        </div>
        <div>
            <button onClick={init} className='btn'>init</button>
            <button onClick={conn} className='btn'>conn</button>
            <button onClick={sub} className='btn'>sub</button>
            <button onClick={signMsg} className='btn'>signMsg</button>
            <button onClick={transferToAddress} className='btn'>transferToAddress</button>
        </div>
    </div>)
}